import list from './js/data.js';
import './css/index.css';
let ul = document.querySelector('.content > ul');
let prevBtn = document.querySelector('.prev');
let nextBtn = document.querySelector('.next');
let totalBox = document.querySelector('.total');
let selectBox = document.querySelector('select');

let totalPage = Math.ceil(list.length / selectBox.value);
let currPage = 1;
totalBox.innerText = `${currPage} / ${totalPage}`;
render();
// 按钮状态更新
function btnChange() {
  if (currPage >= totalPage) {
    nextBtn.classList.add('disable');
    prevBtn.classList.remove('disable');
  } else if (currPage <= 1) {
    nextBtn.classList.remove('disable');
    prevBtn.classList.add('disable');
  } else {
    nextBtn.classList.remove('disable');
    prevBtn.classList.remove('disable');
  }
}
// 页面渲染
function render() {
  if (currPage > totalPage) {
    currPage = totalPage;
    return;
  }
  // 每页渲染个数
  let num = selectBox.value;
  // 当前页码
  let pageNum = Number(totalBox.innerText.slice(0, 1));
  // console.log("pageNum", pageNum);
  ul.innerHTML = '';
  for (
    let i = (pageNum - 1) * num;
    i <= pageNum * num - 1 && i < list.length;
    i++
  ) {
    ul.innerHTML += `<li>
          <img
            src="${list[i].pic}"
            alt=""
          />
          <p>${list[i].name}</p>
          <p>城市: ${list[i].city}</p>
          <p>地址: ${list[i].address}</p>
          <p>价格: ${list[i].price}</p>
          <p>演出时间: ${list[i].showTime}</p>
        </li>
        `;
  }
}

// 选择框的文本更新
selectBox.addEventListener('change', () => {
  totalPage = Math.ceil(list.length / selectBox.value);
  totalBox.innerText = `${currPage} / ${totalPage}`;
  if (currPage > totalPage) {
    currPage = totalPage;
    totalBox.innerText = `${currPage} / ${totalPage}`;
  }
  render();
  btnChange();
});

// 上一页按钮更新
prevBtn.addEventListener('click', () => {
  // console.log("上一张");
  currPage--;
  if (currPage <= 1) currPage = 1;
  totalBox.innerText = `${currPage} / ${totalPage}`;
  render();
  btnChange();
});

// 下一页按钮更新
nextBtn.addEventListener('click', () => {
  // console.log("下一张");
  currPage++;
  if (currPage >= totalPage) {
    totalBox.innerText = `${totalPage} / ${totalPage}`;
  } else {
    totalBox.innerText = `${currPage} / ${totalPage}`;
  }
  render();
  btnChange();
});
